<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;


use App\CustHub\Model\ChUser;
use App\CustHub\Service\ChGetMoneyLogService;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractMapper;
use Mine\MineModel;


class ChGetUserMapper extends AbstractMapper
{
    #[Inject]
    protected ChGetMoneyLogService $log;

    public function assignModel(): void
    {
        $this->model = ChUser::class;
    }


    public function getUser($params): array
    {
        $filters = [
            'id' => '=',
            'nickname' => 'like',
            'mobile' => '=',
            'status' => '=',];
        // 查询 parent_id 为 0 的用户并选择所需字段
        $query =  $this->model::query()
            ->select(['id','nickname','avatar','mobile','status',
                'seat_count','corp_seat_count','login_time','money','created_at','remark'])
            ->where('parent_id','=',0)
            ->orderBy('id','desc');
        $query = applyFilters($query, $params,$filters);
        $paginate = $query->paginate((int) ($params['pageSize'] ?? MineModel::PAGE_SIZE));
        return $this->setPaginate($paginate);
    }

    public function update($id,array $data): bool
    {
        $beforeMoney = $this->model::query()->where('id', $id)->lockForUpdate()->value('money');

        $this->filterExecuteAttributes($data, true);
        $this->model::query()->where('id', $id)->update($data);

        $afterMoney = $this->model::query()->where('id', $id)->value('money');

        if($beforeMoney != $afterMoney) {
            $moneyDifference = abs($afterMoney - $beforeMoney);

            $data =[
                'uid' => $id,
                'before' => $beforeMoney,
                'after' => $afterMoney,
                'money' => $moneyDifference,
                'business_type' => 0,
                'order_id' => '0',
                ];

                $this->log->save($data);
        }
        return true;
    }
}
